package com.lx.config;

import com.lx.pojo.User;
import com.lx.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==》授权AuthorizationInfo方法");
        //获取当前登录用户
        User user = (User) principalCollection.getPrimaryPrincipal();
        User userPerms = userService.getUserByName(user.getName());


        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加授权
        info.addStringPermission(userPerms.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.getUserByName(userToken.getUsername());

        if(user!=null){
            if(!userToken.getUsername().equals(user.getName())){
                //抛出异常
                return null;
            } else { //认证成功，将用户数据存储到session中
                Subject subject = SecurityUtils.getSubject();
                Session session = subject.getSession();
                session.setAttribute("loginUser",user);
            }
        } else {
            return null;
        }

        System.out.println("执行了==》认证AuthenticationToken方法");
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
